import React, { memo, useState } from "react"
import type { FC, ReactNode } from "react"
import { LockOutlined, MailOutlined, UserOutlined } from "@ant-design/icons"
import { Button, Form, Input, message } from "antd"
import { useNavigate } from "react-router-dom"
import type { LoginInterface } from "../../types"
import http from "../../utils/http"
import "./index.css"
interface IProps {
  children?: ReactNode
}
const Login: FC<IProps> = () => {
  const navigate = useNavigate()
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const onFinish = async (values: LoginInterface) => {
    setIsLoading(true)
    try {
      const res = await http.post("/api/v1/auth/login", values)
      console.log(res)
      const { code, data } = res.data
      if (code === 200) {
        message.success("登录成功")
        localStorage.setItem("token", data.token)
        localStorage.setItem("userInfo", JSON.stringify(data.user))
        navigate("/pm-react")
      }
    } catch (error) {
      console.error(error)
    } finally {
      setIsLoading(false)
    }
  }
  return (
    <div className="log-container">
      <div className="log-form">
        <h2>欢迎登录</h2>
        <Form
          name="register"
          initialValues={{ remember: true }}
          style={{ maxWidth: 360 }}
          onFinish={onFinish}>
          <Form.Item
            name="email"
            rules={[{ required: true, message: "请输入你的邮箱!" }]}>
            <Input prefix={<MailOutlined />} placeholder="邮箱" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入你的密码" }]}>
            <Input
              prefix={<LockOutlined />}
              type="password"
              placeholder="密码"
            />
          </Form.Item>
          <Form.Item>
            <Button loading={isLoading} block type="primary" htmlType="submit">
              登录
            </Button>
            <Button
              style={{ marginTop: "2rem" }}
              type="text"
              onClick={() => navigate("/")}>
              没有账号去注册
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default memo(Login)
